package response

import (
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/net/ghttp"
)

//响应结果
const (
	StatusFail            = -1  //失败
	StatusOK              = 200 //成功
	StatusBadRequest      = 400 //错误的请求
	StatusUnauthorized    = 401 //未认证
	StatusForbidden       = 403 //无权限
	StatusValidFail       = 422 //验证失败
	StatusTooManyRequests = 429 //请求过多
	StatusError           = 500 //错误
)

// 数据返回通用数据结构
type Response struct {
	Code int         `json:"code"` // 错误码((0:成功, 1:失败, >1:错误码))
	Msg  string      `json:"msg"`  // 提示信息
	Data interface{} `json:"data"` // 返回数据(业务接口定义具体数据结构)
}

// 标准返回结果数据结构封装。
func Result(r *ghttp.Request, code int, message string, data ...interface{}) {
	responseData := interface{}(nil)
	if len(data) > 0 {
		responseData = data[0]
	}
	if responseData == nil {
		responseData = map[string]interface{}{}
	}

	var content = &Response{
		Code: code,
		Msg:  message,
		Data: responseData,
	}

	// 根据配置设置编码
	format := g.Cfg().GetString("server.defaultFormat")
	switch {
	case format == "json":
		r.Response.WriteJsonExit(content)
	case format == "xml":
		r.Response.WriteXmlExit(content)
	case format == "html":
		r.Response.WriteExit(content)
	case format == "jsonp":
		r.Response.WriteJsonPExit(content)
	default:
		r.Response.WriteJsonExit(content)
	}
}
